#include"sock.hpp"
#include<sys/stat.h>
#include<fstream>
#define WWWROOT "./wwwroot/"
#define HOME_PAGE "index.html"//路径
//其中wwwroot就叫web根目录，wwwroot目录下放置的内容，叫做资源
//wwwroot目录下的index.html叫做网站首页

void Usage(char* str)
{
  cout<<"Usage:" <<str<<" port"<<endl;
  exit(1);
}

void* Hander(void* arg)
{
  int sock = *((int*)arg);
  pthread_detach(pthread_self());
#define SIZE 1024*10
  char buffer[SIZE]={0};

  ssize_t s =recv(sock,buffer,SIZE,0);
  if(s>0)
  {
    buffer[s]= '\0';
    cout<<buffer<<endl;
    //重定向
   // string respon = "http/1.1 301 Permanently moved\n";
 //  string respon = "http/1.1 302 Found\n";//重定向
 //   respon+="Location: https://www.baidu.com/\n";// 
   // respon+="\n";
    //send(sock,respon.c_str(),respon.size(),0);
            
    //响应正文为字符串
    //  string http_response = "http/1.0 200 OK\n";//状态行
    //  http_response+="Content-Type: text/plain\n";//响应报头
    //  http_response+="\n";//空行
    //  string str = "hello linux http!!";    //响应正文
    //  http_response+=str;
    //  send(sock,http_response.c_str(),http_response.size(),0);
    //  响应为文件网页
     string html_file = WWWROOT;
   html_file+=HOME_PAGE;
   //正文部分
   ifstream in(html_file);
   if(!in.is_open())
   {
     string http_response = "http/1.0 404 NOT Found\n";//状态行
     http_response+="Content-Type: text/html; charset=utf8\n";//响应报头      
     http_response+="\n";
     http_response+="<html><p>你访问的资源不存在</p></html>";
     send(sock,http_response.c_str(),http_response.size(),0);//发送 
   }
   else 
   {
     struct stat st;
     stat(html_file.c_str(),&st);
     //返回的时候，有正文的网页信息，还有http的请求
     string line;
     string http_response = "http/1.0 200 OK\n";//状态行
     http_response+="Content-Type: text/html; charset=utf8\n";//响应报头      
     http_response+="Conten-Length: ";
     http_response+=to_string(st.st_size);
     http_response+="\n";
     //set-Cookie:服务器向浏览器设置一个Cookie
     http_response+="Set-Cookie: id=123456\n"; 
     http_response+="\n";
     string content;
     while(getline(in,line))
     {
       content+=line;
     }
     http_response+=content;//正文
     send(sock,http_response.c_str(),http_response.size(),0);//发送
     in.close();
   }
  }
  close(sock);
  return nullptr;
}

int main(int argc,char* argv[])
{
  if(argc!=2)
  {
    Usage(argv[0]);
  }

  uint16_t port =atoi( argv[1]);
  int listen_sock = Sock::Socket();
  Sock::Bind(listen_sock,port);
  Sock::Listen(listen_sock);

  while(1)
  {
    int sock = Sock::Accept(listen_sock);
    if(sock>0)
    {
      int* arg = new int(sock);
      pthread_t ptid;
      pthread_create(&ptid,nullptr,Hander,arg);
      // close(sock);
    }
  }
  return 0;
}
